package com.neusoft.neuiotms.dcam.fixed.controller;

import java.util.Map;

import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.cxf.common.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neusoft.bizcore.activiti.dto.WorkorderDTO;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.neuiotms.common.constant.AHConstants;
import com.neusoft.neuiotms.dcam.anhui.itsm.ApproveResultBean;
import com.neusoft.neuiotms.dcam.anhui.itsm.ContractBean;
import com.neusoft.neuiotms.dcam.fixed.service.ContractService;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.service.ArrivialService;
import com.neusoft.neuiotms.dcam.workflow.service.BaofeiKJService;
import com.neusoft.neuiotms.dcam.workflow.service.DiaoboKJService;
import com.neusoft.neuiotms.dcam.workflow.service.GenghuanKJService;
import com.neusoft.neuiotms.dcam.workflow.service.LingyongKJService;
import com.neusoft.neuiotms.dcam.workflow.service.RukuKJService;
import com.neusoft.neuiotms.dcam.workflow.service.TuikuKJService;
import com.neusoft.neuiotms.dcam.workflow.service.WeixiuKJService;
import com.neusoft.neuiotms.micro.auth.AuthMicroService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "ITSM对接")
@RestController
@RequestMapping(value = "/api/w/itsm")
public class ItsmController {

    @Autowired
    private ContractService contractService;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ArrivialService arrivialService;
    @Autowired
    private TuikuKJService tuikuKJService;
    @Autowired
    private LingyongKJService lingyongKJService;
    @Autowired
    private BaofeiKJService baofeiKJService;
    @Autowired
    private WeixiuKJService weixiuKJService;
    @Autowired
    private DiaoboKJService diaoboKJService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private AuthMicroService authMicroService;
    @Autowired
    private RukuKJService rukuKJService;
    @Autowired
    private GenghuanKJService genghuanKJService;

    @ApiOperation("创建合同")
    @PostMapping("/contract")
    public ResultDTO<?> create(@RequestBody final ContractBean bean) {
        // 创建合同
        this.contractService.createFromItsm(bean);
        if (!CollectionUtils.isEmpty(bean.getAssetList())) {
            // 生成工单
            this.rukuKJService.itsmCreate(bean);
        }
        return ResultDTO.success();
    }

    @ApiOperation("ITSM资产审批结果通知给资产系统")
    @PostMapping("/entry")
    public ResultDTO<?> entry(@RequestBody final ApproveResultBean bean) {
        ItsmController.log.info("ITSM：审批结果: {}", JsonUtils.pojoToJson(bean));

        final Map<String, Object> params = new HashedMap<>();
        params.put("s_roleCode", AHConstants.ROLE_KJ_ASSET_ADMIN);
        final ResultListDTO<Map<String, Object>> results = this.authMicroService.userIndex(params);

        final Map<String, Object> defaultAssetAdmin = results.getData().stream()
                .filter(it -> "liuting".equals(it.get("username"))).findFirst().orElse(results.getData().get(0));

        //        final Map<String, Object> kjAssetAdmin = results.getData().get(0);
        final UserBean user = new UserBean();
        user.setUsername((String) defaultAssetAdmin.get("username"));
        WorkorderDTO workorderDTO;
        try {
            workorderDTO = this.workOrderService.details(bean.getWorkNum());
        } catch (final Exception e) {
            return ResultDTO.failure("工单不存在");
        }

        final Task task =
                this.taskService.createTaskQuery().processInstanceId(workorderDTO.getInstanceId()).singleResult();

        if (null == task) {
            return ResultDTO.success();
        }

        final String workorderType = workorderDTO.getType();
        if ("arrival".equals(workorderType)) {
            if (bean.getResult() == 0) {
                final ITSMApproveDTO dto = new ITSMApproveDTO();
                dto.setWorkOrderNum(bean.getWorkNum());
                dto.setResult("1");
                dto.setTaskId(task.getId());
                this.arrivialService.itsmCreate(dto, user);
            } else {
                // 入库没有驳回处理
            }
        } else if ("RukuKJ".equals(workorderType)) {
            if (bean.getResult() == 0) {
                final ITSMApproveDTO dto = new ITSMApproveDTO();
                dto.setWorkOrderNum(bean.getWorkNum());
                dto.setResult("1");
                dto.setTaskId(task.getId());
                this.rukuKJService.itsmCreate(dto, user);
            } else {
                // 入库没有驳回处理
            }
        } else {
            final ITSMApproveDTO dto = new ITSMApproveDTO();
            dto.setWorkOrderNum(bean.getWorkNum());
            dto.setResult(bean.getResult() == 0 ? "1" : "0");
            dto.setTaskId(task.getId());
            switch (workorderType) {
            case "TuikuKJ":
                this.tuikuKJService.itsmCreate(dto, user);
                break;
            case "LingyongKJ":
                this.lingyongKJService.itsmCreate(dto, user);
                break;
            case "BaofeiKJ":
                this.baofeiKJService.itsmCreate(dto, user);
                break;
            case "WeixiuKJ":
                this.weixiuKJService.itsmCreate(dto, user);
                break;
            case "DiaoboKJ":
                this.diaoboKJService.itsmCreate(dto, user);
                break;
            case "GenghuanKJ":
                this.genghuanKJService.itsmCreate(dto, user);
                break;
            default:
                break;
            }
        }

        return ResultDTO.success();
    }

}
